package com.at.bilibili.service;

import com.at.bilibili.dao.FileDao;
import com.at.bilibili.domain.File;
import com.at.bilibili.service.util.FastDFSUtil;
import com.at.bilibili.service.util.MD5Util;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;


@Service
public class FileService {

    @Autowired
    private FileDao fileDao;
    @Autowired
    private FastDFSUtil fastDFSUtil;

    public String uploadFileBySlices(MultipartFile slice,
                                     String fileMd5,
                                     Integer sliceNo,
                                     Integer totalSliceNo) throws Exception {
        File dbFileMD5 = fileDao.getFileByMD5(fileMd5);
        /**
         * 秒传  :: 之前上传过
         */
        if (dbFileMD5 != null){
            return dbFileMD5.getUrl();
        }
        String url = fastDFSUtil.uploadFileBySlices(slice, fileMd5, sliceNo, totalSliceNo);
        // 将上传的文件 存入t_file
        if (!StringUtils.isNullOrEmpty(url)){
            File file = new File();
            file.setCreateTime(new Date());
            file.setMd5(fileMd5);
            file.setType(fastDFSUtil.getFileType(slice));
            file.setUrl(url);
            fileDao.addFile(file);
        }
        return url;
    }


    public String getFileMd5(MultipartFile file) throws Exception {
        return MD5Util.getFileMD5(file);
    }

    public File getFileByMd5(String fileMd5) {
        return fileDao.getFileByMD5(fileMd5);
    }
}
